package cn.com.open.itembank.logic.questiontype;

import cn.com.open.itembank.common.enums.Source;
import cn.com.open.itembank.common.enums.YesOrNo;
import cn.com.open.itembank.dto.ImportParameter;
import cn.com.open.itembank.dto.QuestionImportModel;
import cn.com.open.itembank.dto.QuestionModel;
import cn.com.open.itembank.entity.QuestionCategory;
import cn.com.open.itembank.entity.QuestionType;
import cn.com.open.itembank.utils.StringUtil;

import java.util.*;

/**
 * The type Question type base.
 */
public class QuestionTypeBase {
    /**
     * 试题输入模型.
     */
    protected QuestionImportModel importModel;

    /**
     * 导入参数.
     */
    protected ImportParameter importParameter;

    /**
     * 试题题型模型.
     */
    protected QuestionType questionType;

    /**
     * 可用应用类别列表.
     */
    protected List<QuestionCategory> categories;

    /**
     * 题库可用题型列表.
     */
    protected List<QuestionType> questionTypes;

    /**
     * 课程外部资源章节目录树json.
     */
    protected List<Map<String, String>> outerChapterList;

    /**
     * 构造函数.
     *
     * @param model the model
     */
    public QuestionTypeBase(QuestionImportModel model) {

        //region 格式化
        for (QuestionImportModel item : model.getSubItems()) {
            for (String choice : item.getChoices()) {
                formatString(choice);
            }

            for (String answer : item.getAnswer()) {
                formatString(answer);
            }

            item.setPrompt(formatString(item.getPrompt()));
        }

        for (String item : model.getChoices()) {
            formatString(item);
        }

        for (String item : model.getAnswer()) {
            formatString(item);
        }

        model.setPrompt(formatString(model.getPrompt()));
        //endregion
        this.categories = new ArrayList<>();
        this.questionTypes = new ArrayList<>();
        this.outerChapterList = new ArrayList<>();
        this.importModel = model;

        diffMap.put("难", 0.1f);
        diffMap.put("较难", 0.3f);
        diffMap.put("中", 0.5f);
        diffMap.put("较易", 0.7f);
        diffMap.put("易", 0.9f);
    }

    //region 属性

    /**
     * Gets import model.
     *
     * @return the import model
     */
    public QuestionImportModel getImportModel() {
        return importModel;
    }


    /**
     * Sets import model.
     *
     * @param importModel the import model
     */
    public void setImportModel(QuestionImportModel importModel) {
        this.importModel = importModel;
    }

    /**
     * Gets import parameter.
     *
     * @return the import parameter
     */
    public ImportParameter getImportParameter() {
        return importParameter;
    }

    /**
     * Sets import parameter.
     *
     * @param importParameter the import parameter
     */
    public void setImportParameter(ImportParameter importParameter) {
        this.importParameter = importParameter;
    }

    /**
     * Gets question type.
     *
     * @return the question type
     */
    public QuestionType getQuestionType() {
        return questionType;
    }

    /**
     * Sets question type.
     *
     * @param questionType the question type
     */
    public void setQuestionType(QuestionType questionType) {
        this.questionType = questionType;
    }

    /**
     * Gets categories.
     *
     * @return the categories
     */
    public List<QuestionCategory> getCategories() {
        return categories;
    }

    /**
     * Sets categories.
     *
     * @param categories the categories
     */
    public void setCategories(List<QuestionCategory> categories) {
        this.categories = categories;
    }

    /**
     * Gets question types.
     *
     * @return the question types
     */
    public List<QuestionType> getQuestionTypes() {
        return questionTypes;
    }

    /**
     * Sets question types.
     *
     * @param questionTypes the question types
     */
    public void setQuestionTypes(List<QuestionType> questionTypes) {
        this.questionTypes = questionTypes;
    }

    /**
     * Gets outer chapter list.
     *
     * @return the outer chapter list
     */
    public List<Map<String, String>> getOuterChapterList() {
        return outerChapterList;
    }

    /**
     * Sets outer chapter list.
     *
     * @param outerChapterList the outer chapter list
     */
    public void setOuterChapterList(List<Map<String, String>> outerChapterList) {
        this.outerChapterList = outerChapterList;
    }

    //endregion

    /**
     * The Answer id list.
     */
    protected List<String> answerIdList = Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");

    /**
     * The Split separate tag.
     */
    protected String splitSeparateTag = "##";

    /**
     * The Diff map.
     */
    protected Map<String, Float> diffMap = new HashMap<>();

    /**
     * 是否必须检查选项
     */
    protected boolean mustHasChoice = false;

    //region 校验是否为空

    /**
     * 校验是否为空.
     *
     * @return the boolean
     */
    protected boolean checkEmptySelf() {
        boolean result = true;

        if (mustHasChoice && importModel.getChoices().isEmpty()) {
            importModel.setErrorInfo("选项不能为空；");
            result = false;
        }

        if (importModel.getAnswer().isEmpty() && !importModel.getQuestionTypeName().equals("匹配题") && !importModel.getQuestionTypeName().equals("配伍题")) {
            importModel.setErrorInfo("答案不能为空；");
            result = false;
        }

        return result;
    }
    //endregion

    //region 校验难度

    /**
     * 校验难度.
     *
     * @return the boolean
     */
    public boolean checkDifficulty() {

        boolean result = true;

        if (diffMap.containsKey(importModel.getSaveDiffWord())) {
            importModel.setDifficulty(diffMap.get(importModel.getSaveDiffWord()).toString());
        } else {
            importModel.setErrorInfo("难度文字不正确；");
            result = false;
        }

        return result;
    }
    //endregion

    //region 校验章节

    /**
     * 校验章节.
     *
     * @return the boolean
     */
    public boolean checkChapter() {
        //如果导入参数中设置了章节id，则以此为准
        if (!StringUtil.isEmpty(importParameter.getChapterId())) {
            importModel.setChapter(importParameter.getChapterId());
            return true;
        }

        //根据导入参数中设置的来源，也就是课程的来源确定读取章节的来源
        if (importParameter.getSource() == Source.OUTER.getIndex()) {
            return checkOuterChapter();
        } else {
            return checkInnerChapter();
        }
    }

    /**
     * 校验外部课程的章节.
     *
     * @return the boolean
     */
    private boolean checkOuterChapter() {

        if (outerChapterList.isEmpty()) {
            importModel.setErrorInfo("资源课程章节信息获取失败；");
            return false;
        }

        if (StringUtil.isEmpty(importModel.getChapter())) {
            importModel.setChapter(importParameter.getItemBankId());
            return true;
        }

        for (Map<String, String> map : outerChapterList) {
            if (map.get("name").equalsIgnoreCase(importModel.getChapter())) {
                importModel.setChapter(map.get("id"));
                return true;
            }
        }

        importModel.setErrorInfo("章节有误；");
        return false;
    }

    /**
     * 校验内部课程的章节.
     *
     * @return the boolean
     */
    private boolean checkInnerChapter() {
        //如果章节赋值则需要验证并且返回id，如果没有赋值，则需要获取课程对应的根章节
        //此处默认暂时先获取题库id
        importModel.setChapter(importParameter.getItemBankId());
        return true;
    }
    //endregion

    //region 校验试题类别编码

    /**
     * 校验试题类别编码.
     *
     * @return the boolean
     */
    public boolean checkQuestionCategory() {
        boolean result = false;

        for (QuestionCategory category : categories) {
            if (category.getQuestionCategoryName().equalsIgnoreCase(importModel.getQuestionCategoryName())) {
                importModel.setQuestionCategory(category.getQuestionCategoryID());
                result = true;
            }
        }

        if (!result) {
            importModel.setErrorInfo("试题类别有误；");
            result = false;
        }

        return result;
    }

    //endregion

    //region 校验填空数与答案数是否匹配

    /**
     * 校验填空数与答案数是否匹配.
     *
     * @return the boolean
     */
    protected boolean checkAnswerCount() {
        return true;
    }
    //endregion

    //region 校验分数格式及是否为零

    /**
     * 校验分数格式及是否为零.
     *
     * @return the boolean
     */
    public boolean checkScoreFormat() {
        boolean result = true;

        try {
            Double score = Double.parseDouble(importModel.getScore());

            if (score == 0) {
                importModel.setErrorInfo("分值不能为零；");
                result = false;
            }
        } catch (Exception e) {
            importModel.setErrorInfo("分值格式不正确；");
            result = false;
        }

        return result;
    }
    //endregion

    //region 校验答案格式

    /**
     * 校验答案格式.
     *
     * @return the boolean
     */
    protected boolean checkAnswerFormat() {
        return true;
    }
    //endregion

    //region 校验答案界限

    /**
     * 校验答案界限.
     *
     * @return the boolean
     */
    protected boolean checkAnswerLimit() {
        boolean result = true;

        for (String item : importModel.getAnswer()) {
            if (answerIdList.indexOf(item.trim().toUpperCase()) > importModel.getChoices().size() - 1 && !importModel.getQuestionTypeName().equals("组合题")) {
                importModel.setErrorInfo("答案英文字符超出界限；");
                return false;
            }
        }

        return result;
    }
    //endregion

    //region 校验选项与答案数量是否匹配

    /**
     * 校验选项与答案数量是否匹配.
     *
     * @return the boolean
     */
    protected boolean checkMatch() {
        return true;
    }
    //endregion

    //region 校验子题数是否匹配

    /**
     * 校验填空数与答案数是否匹配.
     *
     * @return the boolean
     */
    protected boolean checkQuestionCount() {
        return true;
    }
    //endregion

    //region 校验子题型

    /**
     * 校验子题型.
     *
     * @return the boolean
     */
    protected boolean checkSubQuestionType() {
        return true;
    }
    //endregion

    //region 校验

    /**
     * 校验.
     *
     * @return the boolean
     */
    public boolean checkSummary() {
        boolean result = checkEmptySelf();

        if (result) {
            List<Boolean> resultList = new ArrayList<>();

            result = checkDifficulty();
            resultList.add(result);
            result = checkChapter();
            resultList.add(result);
            result = checkQuestionCategory();
            resultList.add(result);
            result = checkAnswerFormat();
            resultList.add(result);

            result = checkAnswerLimit();
            resultList.add(result);
            result = checkAnswerCount();
            resultList.add(result);
            result = checkScoreFormat();
            resultList.add(result);

            result = checkMatch();
            resultList.add(result);

            result = checkQuestionCount();
            resultList.add(result);
            result = checkSubQuestionType();
            resultList.add(result);

            for (boolean check : resultList) {
                if (!check) {
                    result = false;
                    break;
                }
            }
        }
        return result;
    }
    //endregion

    //region 获取保存模型

    /**
     * 获取保存模型.
     *
     * @return the input question model
     */
    public QuestionModel getSaveModel() {
        //需要改成生成 QuestionModel 模型，调用统一的新增试题接口即可
        QuestionModel model = new QuestionModel();

        model.setI2(formatString(importModel.getPrompt()));
        model.setI3(questionType.getQuestionInnerTypeID());
        model.setI4(importParameter.getItemBankId());
        model.setI5(importModel.getChapter());
        //I6,I7 需要各种题型重载完成
        model.getI8().add(importModel.getQuestionCategory());
        model.setI9(Double.parseDouble(importModel.getScore()));
        model.setI10(importModel.getQuestionAnalysis().replace("[br]", "<br>"));
        model.setI11(YesOrNo.NO.getIndex());
        model.setI12("");
        model.setI13(Double.parseDouble(importModel.getDifficulty()));
        model.setI14(importParameter.getOrganizationId());
        //I17 需要各种题型重载完成
        model.setI17(0);
        model.setI21(questionType.getQuestionTypeName());
        model.setI22(importParameter.getUserId());
        model.setI25(YesOrNo.YES.getIndex());
        model.setI30(questionType.getSectionID());
        //importModel的objective的true表示是客观题,i32的客观题0，主观题1
        model.setI32(0);

        return model;
    }
    //endregion

    //region 格式化文本

    /**
     * 格式化文本.
     *
     * @param orginalString the orginal string
     * @return the string
     */
    public String formatString(String orginalString) {
        String result = orginalString.trim();

        //将导入的换行替换成标准格式
        result = result.replace("[br]", "<br>");

        return result;
    }

    //endregion
}
